package com.lottery.service.pc28.accoutService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.pc28.accoutDao.LoaclauthDao;
import com.lottery.dao.pc28.accoutDao.LoginInfoDao;
import com.lottery.dao.pc28.accoutDao.OauthDao;
import com.lottery.dao.pc28.accoutDao.UserDao;
import com.lottery.dao.pc28.wealthDao.AccountDao;
import com.lottery.dto.UtilsDto;
import com.lottery.entity.*;
import com.lottery.service.pc28.JedisClient;
import com.lottery.service.pc28.accoutService.JavaSmsApi;
import com.lottery.service.pc28.accoutService.LocalauthService;
import com.lottery.service.pc28.robotService.RobotUserService;
import com.lottery.utils.CustomerContext;
import com.lottery.utils.DateUtil;
import com.lottery.utils.RandCodeUtil;
import com.lottery.utils.TouristData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


public class LoaclauthServiceimpl implements LocalauthService {

	@Autowired
	private LoaclauthDao loaclauthdao;

	@Autowired
	private UserDao userdao;

	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private LoginInfoDao logindao;

	@Autowired
	private AccountDao accountDao;

	@Autowired
	private OauthDao oauthDao;

	// 用户token的key
	@Value("${TOKEN}")
	private String TOKEN;

	// #用户微信登录token的key
	@Value("${TOKEN1}")
	private String TOKEN1;

	// #生成的验证码以key存储进 jedis
	@Value("${LOGINSYSTEM}")
	private String LOGINSYSTEM;

	// #生成的手机短信验证码以 key的 形式存储
	@Value("${LOGINSYSTEM1}")
	private String LOGINSYSTEM1;

	@Value("${SMSKEY}")
	private String SMSKEY;

	@Value("${SMSSMARK}")
	private String SMSSMARK;

	public static Map<Integer, Integer> onlineMap = new ConcurrentHashMap<Integer, Integer>();

	public static Map<Integer, String> ssoMap = new ConcurrentHashMap<Integer, String>();

	// 日志
	private final Logger logger = LoggerFactory.getLogger(this.getClass());



	/**
	 * 校验注册
	 *1 user信息
	 * 2 登入信息
	 * 3 账户金额
	 * 一项失败所有回滚
	 * @param phone_num
	 * @param password
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void regist(String username, String password, String agencyId)throws Exception{
		//还可以加入相关判断,并针对性处理
		User user = new User();
		String nikename = RandCodeUtil.randCode(5);
		user.setUserName(nikename);
		user.setUserType(1);
		String createTime =DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss");
		user.setCreateTime(createTime);
		//判断用户是否有渠道商推荐码,没有则为平台默认用户
		if(agencyId.trim().isEmpty()){
			user.setAgencyId("88888");
		}else{
			user.setAgencyId(agencyId);
		}
		userdao.insertUser(user);
		//获取自增生成的ID,并将用户名和密码存入loaclauth表
		int userId = user.getUserId();
		Loaclauth loaclauth = new Loaclauth();
		loaclauth.setuserId(userId);
		loaclauth.setPhoneNum(username);
		loaclauth.setPassword(password);
		loaclauthdao.insertloaclauth(loaclauth);
		// 注册成功后，向账户表插入一条数据（user_id）
		Account account = new Account();
		account.setUserId(userId);
		accountDao.insertAccount(account);
	}
	/*public String regist(String phoneNum, String password, String smscode, String agencyId, String recommendCode,
			String city) throws Exception {
		JSONObject jObject = new JSONObject();
		if (phoneNum == null || phoneNum.trim().isEmpty()) {
			jObject.put("result", "1");
			jObject.put("msg", "手机号不能为空");
			return jObject.toJSONString();
		}

		// if (city == null || city.trim().isEmpty()) {
		// jObject.put("result", "5");
		// jObject.put("msg", "所在城市不能为空");
		// return jObject.toJSONString();
		// }

		if (phoneNum.startsWith("1") && phoneNum.length() == 11) {
			try {
				Long i = Long.parseLong(phoneNum);
				logger.info("phoneNum:{}", i);
			} catch (Exception e) {
				e.printStackTrace();
				jObject.put("result", "2");
				jObject.put("msg", "手机号不正确");
				return jObject.toJSONString();
			}
		} else {
			jObject.put("result", "2");
			jObject.put("msg", "手机号不正确");
			return jObject.toJSONString();
		}
		// String reg = "(1[0-9])\\d{10}$";
		// if (!phone_num.matches(reg)) {
		// throw new UserphoneNumException("不合规则");
		// }
		// 判断短信 验证码

		if (smscode == null || smscode.trim().isEmpty()) {
			jObject.put("result", "1");
			jObject.put("msg", "短信验证码不能为空");
			return jObject.toJSONString();
		}
		String jse = jedisClient.get(LOGINSYSTEM1 + phoneNum);
		logger.info("jedis smscode:" + jse);
		// 判断验证码是否一致
		if (!smscode.equals(jse)) {
			jObject.put("result", "1");
			jObject.put("msg", "短信验证码不一致");
			return jObject.toJSONString();
		}
		jedisClient.del("loginsystem" + phoneNum);
		// 判断密码
		if (password == null || password.trim().isEmpty()) {
			jObject.put("result", "1");
			jObject.put("msg", "密码不正确");
			return jObject.toJSONString();
		}

		try {
			// 判断推荐码
			// 首先判断有没有分享的这个用户
			// 有就 进一步 判断推荐码不能输入为空，并且 不区分 大小写
			if (agencyId.equals("88888")) { // 代理商88888是自己的平台代码，可以有推荐码，其他代理商均没有推荐码
				if (null != recommendCode && !"".equals(recommendCode.trim())) {
					User selectByMyRecommendCode = userdao.selectByMyRecommendCode(recommendCode);
					if (selectByMyRecommendCode == null) {
						jObject.put("result", "7");
						jObject.put("msg", "没有此邀请码");
						return jObject.toJSONString();
					}
				} else {
					recommendCode = agencyId;
				}
			} else {
				recommendCode = agencyId;
			}
			// 注册插入 手机号
			User user = new User();
			String tmpRecommendCode = RandCodeUtil.randCode(5);
			while (true) {
				User tmpUser = userdao.selectByMyRecommendCode(tmpRecommendCode); // 推荐码要唯一
				if (tmpUser == null)
					break;
				tmpRecommendCode = RandCodeUtil.randCode(5);
			}
			logger.debug("********tmpRecommendCode:{}", tmpRecommendCode);

			user.setPhoneNum(phoneNum);
			user.setUserType(1);
			user.setUserName(RandCodeUtil.randCode(5));
			user.setAgencyId(agencyId);
			user.setCity(city);
			user.setCreateTime(DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss"));
			user.setRecommendCode(recommendCode);
			user.setMyRecommendCode(tmpRecommendCode);
			user.setHeadPic("0");
			// 主键返回 user_id
			userdao.insertUser(user);
			// 注册用户
			logger.info(" password:{}**********", password);
			String pwd = UtilsDto.crypt(password);
			logger.info(" pwd:{}**********", pwd);
			Loaclauth loaclauth = new Loaclauth();
			loaclauth.setuserId(user.getUserId());
			loaclauth.setPhoneNum(phoneNum);
			loaclauth.setPassword(pwd);
			logger.info("user_id:{}, phone_num:{}, password:{}", user.getUserId(), phoneNum, password);
			loaclauthdao.insertloaclauth(loaclauth);
			// 注册成功后，向账户表插入一条数据（user_id）
			Account account = new Account();
			account.setUserId(user.getUserId());
			accountDao.insertAccount(account);
			jObject.put("result", "0");
			jObject.put("msg", "注册成功");
		} catch (Exception e) {
			logger.error("regist error:", e);
			jObject.put("result", "1");
			jObject.put("msg", "注册失败 ，重新注册 ");
			throw new Exception("regist error");
		}

		return jObject.toJSONString();

	}*/




	// 忘记密码
	public String forgetpassword(String phoneNum, String smscode, String password) {
		logger.info(" password:{}**********", password);
		JSONObject jObject = new JSONObject();
		String pwd = UtilsDto.crypt(password);
		logger.info(" pwd:{}**********", pwd);
		try {
			String jse = jedisClient.get(LOGINSYSTEM1 + phoneNum);
			logger.info("jse:{}", jse);
			if (!smscode.equals(jse)) {
				jObject.put("result", "1");
				jObject.put("msg", "短信验证码不正确");
				return jObject.toJSONString();
			}
			// if (phoneNum.startsWith("1") && phoneNum.length() == 11) {
			// try {
			// Long i = Long.parseLong(phoneNum);
			// logger.info("phoneNum:{}", i);
			// } catch (Exception e) {
			// e.printStackTrace();
			// jObject.put("result", "2");
			// jObject.put("msg", "手机号不正确");
			// return jObject.toJSONString();
			// }
			// } else {
			// jObject.put("result", "2");
			// jObject.put("msg", "手机号不正确");
			// return jObject.toJSONString();
			// }

			// jedisClient.del("loginsystem" + phone_num);
			User findUserByUserName = userdao.findUserByUserName(phoneNum);
			if (findUserByUserName == null) {
				jObject.put("result", "3");
				jObject.put("msg", "该手机号没注册！");
				return jObject.toJSONString();
			}

			Loaclauth lauth = new Loaclauth();
			lauth.setPhoneNum(phoneNum);
			lauth.setPassword(pwd);
			loaclauthdao.updatepasswordbyphone(lauth);
			jObject.put("result", "0");
			jObject.put("msg", "重置成功");
		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "2");
			jObject.put("msg", "重置失败");
		}

		logger.info("jObject:{}", jObject.toJSONString());
		return jObject.toJSONString();
	}

	// 修改密码
	@Override
	public String updatepassword(int userId, String oldpassword, String newpassword) {
		JSONObject jObject = new JSONObject();
		logger.info(" oldpassword,newpassword:{},{}**********", oldpassword, newpassword);
		String pwd = UtilsDto.crypt(oldpassword);
		String pwd1 = UtilsDto.crypt(newpassword);
		logger.info(" pwd,pwd1:{},{}**********", pwd, pwd1);

		try {
			// 查询登录表信息
			Loaclauth loaclauth = loaclauthdao.selectId(userId);
			logger.info("loaclauth:{}", loaclauth);
			if (loaclauth == null) {
				jObject.put("result", "1");
				jObject.put("msg", "没有用户");
				return jObject.toJSONString();
			}
			logger.info("pwd:{}--{}", pwd, loaclauth.getPassword());
			if (!pwd.equals(loaclauth.getPassword())) {
				jObject.put("result", "1");
				jObject.put("msg", "原密码错误");
				return jObject.toJSONString();
			}
			Loaclauth lauth = new Loaclauth();
			lauth.setuserId(userId);
			lauth.setPassword(pwd1);
			loaclauthdao.updatepassword(lauth);
			jObject.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "1");
			jObject.put("msg", "重置失败");
		}

		logger.info("jObject:{}", jObject.toJSONString());
		return jObject.toJSONString();
	}

	// 登录
	@Override
	public String login(String phoneNum, String password, String deviceId, String hostAddr, int loginType) {
		JSONObject jObject = new JSONObject();
		User user = new User();
		logger.info("password*******************:{}", password);
		String pwd = UtilsDto.crypt(password);
		logger.info("pwd*******************:{}", pwd);
		// 登录时进行比对
		try {
			if (loginType == 1) {
				String tmpStr = phoneNum + "," + System.currentTimeMillis();
				String token = UtilsDto.crypt(tmpStr);
				jObject.put("token", token);
				String touristName = RandCodeUtil.randCode(5);
				jObject.put("nickName", touristName);

				Long index = jedisClient.incr("touristindex");
				int touristId = (int) (index + 1100000000);
				jedisClient.hset(touristId + "", "amount", 2000 + "");
				jObject.put("userId", touristId);
				jObject.put("loginType", loginType);
				jObject.put("deviceId", deviceId);

				Tourist tourist = new Tourist();
				tourist.setTouristId(touristId);
				tourist.setTouristName(touristName);
				tourist.setDeviceId(deviceId);
				TouristData.touristInfo.put(touristId, tourist);
				jedisClient.set(String.valueOf(TOKEN + touristId), token);
				jedisClient.expire(TOKEN + touristId, 60 * 60);
				jedisClient.expire(touristId + "", 60 * 60);

				//后续还得修改
				ArrayList<Bettinginfo> sscBetList = new ArrayList<Bettinginfo>();
				TouristData.touristBetting.put(touristId, sscBetList);
				ArrayList<Bettinginfo> pc28BetList = new ArrayList<Bettinginfo>();
				TouristData.touristPc28Betting.put(touristId, pc28BetList);
				jObject.put("result", "0");
			}else{
				if (phoneNum == null || phoneNum.trim().isEmpty()) {
					jObject.put("result", "8");
					jObject.put("msg", "用户名为空");
					return jObject.toJSONString();
				}
				if (pwd == null || pwd.trim().isEmpty()) {
					jObject.put("result", "1");
					jObject.put("msg", "密码不能空");
					return jObject.toJSONString();

				}
				logger.info(" username:{}", phoneNum);
				// 查询登录表信息
				Loaclauth loaclauth = loaclauthdao.selectphone(phoneNum);
				logger.info(" loaclauth:{}", loaclauth);
				// 获取登录表中的信息
				if (loaclauth == null) {
					jObject.put("result", "3");
					jObject.put("msg", "用户不存在 ");
					return jObject.toJSONString();
				}
				// 获取数据库中的密码
				// 密码 进行 对比!jse.equals(smscode)
				logger.info("password:{}--{}", pwd, loaclauth.getPassword());
				if (pwd.equals(loaclauth.getPassword())) {

					// 登录成功
					// 返回用户 信息
					LoginInfo login = new LoginInfo();
					// 生成一个token
					String tmpStr = phoneNum + "," + System.currentTimeMillis();
					String token = UtilsDto.crypt(tmpStr);
					// 把token存入login_info
					login.setToken(token);
					login.setUserId(loaclauth.getuserId());
					login.setUserMark(phoneNum);
					login.setLoginTime(System.currentTimeMillis() / 1000);
					login.setHostAddr(hostAddr);
					login.setOnlineNum(onlineMap.size());
					login.setExpire(0);
					login.setStrtime(DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss"));
					logindao.insertloginfo(login);
					// 把token存入jedisClient
					jedisClient.set(String.valueOf(TOKEN + loaclauth.getuserId()), token);

					user = userdao.selectId(loaclauth.getuserId());
					if (user.getState().equals("0")) {
						jObject.put("result", "4");
						jObject.put("msg", "用户被冻结 ");
						return jObject.toJSONString();
					}
					onlineMap.put(loaclauth.getuserId(), (int) (System.currentTimeMillis() / 1000));
					logger.debug("online number:{}", onlineMap.size());
					ssoMap.put(loaclauth.getuserId(), deviceId);

					logger.info("user:{}, phone_num:{}, pwd:{}", user, phoneNum, pwd);
					jObject.put("result", "0");
					jObject.put("userId", loaclauth.getuserId());
					jObject.put("headPic", user.getHeadPic());
					String namestr = user.getUserName();
					jObject.put("nickName", namestr);
					jObject.put("phoneNum", phoneNum);
					jObject.put("city", user.getCity());
					jObject.put("myRecommendCode", user.getMyRecommendCode());
					jObject.put("recommendCode", user.getRecommendCode());
					jObject.put("realName", user.getRealName());
					jObject.put("identityCard", user.getIdentityCard());
					jObject.put("token", token);
				} else {
					jObject.put("result", "4");
					jObject.put("msg", "账户或密码输入错误");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "6");
			jObject.put("msg", "登陆失败");
		}
		return jObject.toJSONString();
	}
/*
	public String login(String phoneNum, String password, String deviceId, String hostAddr, int loginType) {
		JSONObject jObject = new JSONObject();
		User user = new User();
		logger.info("password*******************:{}", password);
		String pwd = UtilsDto.crypt(password);
		logger.info("pwd*******************:{}", pwd);
		// 登录时进行比对
		try {
			if (loginType == 1) {
				String tmpStr = phoneNum + "," + System.currentTimeMillis();
				String token = UtilsDto.crypt(tmpStr);
				jObject.put("token", token);
				String touristName = RandCodeUtil.randCode(5);
				jObject.put("nickName", touristName);

				Long index = jedisClient.incr("touristindex");
				int touristId = (int) (index + 1100000000);
				jedisClient.hset(touristId + "", "amount", 2000 + "");
				jObject.put("userId", touristId);
				jObject.put("loginType", loginType);
				jObject.put("deviceId", deviceId);

				Tourist tourist = new Tourist();
				tourist.setTouristId(touristId);
				tourist.setTouristName(touristName);
				tourist.setDeviceId(deviceId);
				TouristData.touristInfo.put(touristId, tourist);
				jedisClient.set(String.valueOf(TOKEN + touristId), token);
				jedisClient.expire(TOKEN + touristId, 60 * 60);
				jedisClient.expire(touristId + "", 60 * 60);

				//后续还得修改
				ArrayList<Bettinginfo> sscBetList = new ArrayList<Bettinginfo>();
				TouristData.touristBetting.put(touristId, sscBetList);
				ArrayList<Bettinginfo> pc28BetList = new ArrayList<Bettinginfo>();
				TouristData.touristPc28Betting.put(touristId, pc28BetList);
				jObject.put("result", "0");
				return jObject.toJSONString();
			}

			if (phoneNum == null || phoneNum.trim().isEmpty()) {
				jObject.put("result", "8");
				jObject.put("msg", "用户名为空");
				return jObject.toJSONString();
			}
			if (pwd == null || pwd.trim().isEmpty()) {
				jObject.put("result", "1");
				jObject.put("msg", "密码不能空");
				return jObject.toJSONString();

			}
			if (phoneNum.startsWith("1") && phoneNum.length() == 11) {
				try {
					Long i = Long.parseLong(phoneNum);
					logger.info("phoneNum:{}", i);
				} catch (Exception e) {
					e.printStackTrace();
					jObject.put("result", "2");
					jObject.put("msg", "手机号不正确");
					return jObject.toJSONString();
				}
			} else {
				jObject.put("result", "2");
				jObject.put("msg", "手机号不正确");
				return jObject.toJSONString();
			}
			logger.info(" phone_num:{}", phoneNum);
			// 查询登录表信息
			Loaclauth loaclauth = loaclauthdao.selectphone(phoneNum);
			logger.info(" loaclauth:{}", loaclauth);
			// 获取登录表中的信息
			if (loaclauth == null) {
				jObject.put("result", "3");
				jObject.put("msg", "用户不存在 ");
				return jObject.toJSONString();
			}
			// 获取数据库中的密码
			// 密码 进行 对比!jse.equals(smscode)
			logger.info("password:{}--{}", pwd, loaclauth.getPassword());
			if (pwd.equals(loaclauth.getPassword())) {

				// 登录成功
				// 返回用户 信息
				LoginInfo login = new LoginInfo();
				// 生成一个token
				String tmpStr = phoneNum + "," + System.currentTimeMillis();
				String token = UtilsDto.crypt(tmpStr);
				// 把token存入login_info
				login.setToken(token);
				login.setUserId(loaclauth.getuserId());
				login.setUserMark(phoneNum);
				login.setLoginTime(System.currentTimeMillis() / 1000);
				login.setHostAddr(hostAddr);
				login.setOnlineNum(onlineMap.size());
				login.setExpire(0);
				login.setStrtime(DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss"));
				logindao.insertloginfo(login);
				// 把token存入jedisClient
				jedisClient.set(String.valueOf(TOKEN + loaclauth.getuserId()), token);

				user = userdao.selectId(loaclauth.getuserId());
				if (user.getState().equals("0")) {
					jObject.put("result", "4");
					jObject.put("msg", "用户被冻结 ");
					return jObject.toJSONString();
				}
				onlineMap.put(loaclauth.getuserId(), (int) (System.currentTimeMillis() / 1000));
				logger.debug("online number:{}", onlineMap.size());
				ssoMap.put(loaclauth.getuserId(), deviceId);

				logger.info("user:{}, phone_num:{}, pwd:{}", user, phoneNum, pwd);
				jObject.put("result", "0");
				jObject.put("userId", loaclauth.getuserId());
				jObject.put("headPic", user.getHeadPic());
				String namestr = user.getUserName();
				jObject.put("nickName", namestr);
				jObject.put("phoneNum", phoneNum);
				jObject.put("city", user.getCity());
				jObject.put("myRecommendCode", user.getMyRecommendCode());
				jObject.put("recommendCode", user.getRecommendCode());
				jObject.put("realName", user.getRealName());
				jObject.put("identityCard", user.getIdentityCard());
				jObject.put("token", token);
			} else {
				jObject.put("result", "4");
				jObject.put("msg", "账户或密码输入错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "6");
			jObject.put("msg", "登陆失败");
		}
		return jObject.toJSONString();
	}
*/

	// 第三方登录
	@Override
	@Transactional
	public String oauth(String oauthType, String oauthId, String nickName, String headPic, String deviceId,
			String hostAddr) {
		JSONObject jObject = new JSONObject();

		// 判断oauth_type为空时
		if (oauthType == null) {
			jObject.put("result", "1");
			jObject.put("msg", "类型不能为空");
		}

		// 判断oauth_id为空时
		if (oauthId == null) {
			jObject.put("result", "1");
			jObject.put("msg", "id不能为空");
		}
		// 查询表oauth，如果 存在，带出userid，根据userid到表 user_info查找用户信息返回 给客户端
		try {
			Oauth oauth = oauthDao.selectfindByoauthId(oauthId);
			if (oauth != null) {
				// 获取用户的id
				int userId = oauth.getUserId();
				// 根据id来 查询 用户 信息
				// User user = new User();
				User user = userdao.selectId(oauth.getUserId());
				user.setUserName(nickName);
				user.setHeadPic(headPic);
				user.setUserId(userId);
				userdao.updateUser(user);
				// 返回用户 信息
				LoginInfo loginjs = new LoginInfo();
				// 生成一个token
				String tmpStr = oauthId + "," + System.currentTimeMillis();
				String token = UtilsDto.crypt(tmpStr);
				// 把token存入login_info
				loginjs.setToken(token);
				loginjs.setUserId(userId);
				loginjs.setUserMark(oauthId);
				loginjs.setHostAddr(hostAddr);
				loginjs.setLoginTime(System.currentTimeMillis() / 1000);
				loginjs.setExpire(0);
				logindao.insertloginfo(loginjs);

				// 把token存入jedisClient
				jedisClient.set(String.valueOf(TOKEN1 + oauth.getUserId()), token);
				onlineMap.put(userId, (int) (System.currentTimeMillis() / 1000));
				ssoMap.put(userId, deviceId);

				logger.info("oauth:{}, oauth_id:{}, oauth_type:{}, nick_name:{}, head_pic:{}", oauth, oauthId,
						oauthType, nickName, headPic);
				jObject.put("result", "0");
				jObject.put("userId", oauth.getUserId());
				jObject.put("nickName", nickName);
				jObject.put("headPic", headPic);
				jObject.put("phoneNum", user.getPhoneNum());
				jObject.put("myRecommendCode", user.getMyRecommendCode());
				jObject.put("realName", user.getRealName());
				jObject.put("identityCard", user.getIdentityCard());
				jObject.put("token", token);
			} else { // 如果不存在插入user_info，插入oauth，返回成功
				// 插入用户类型,昵称 ，图像地址
				oauth = new Oauth();
				User user = new User();
				user.setUserType(1);
				user.setUserName(nickName);
				user.setHeadPic(headPic);

				String tmpRecommendCode = RandCodeUtil.randCode(5); // 生成5位的随机码
				while (true) {
					User tmpUser = userdao.selectByMyRecommendCode(tmpRecommendCode); // 推荐码要唯一
					if (tmpUser == null)
						break;
					tmpRecommendCode = RandCodeUtil.randCode(5);
				}
				logger.debug("********tmpRecommendCode:{}", tmpRecommendCode);

				user.setMyRecommendCode(tmpRecommendCode);
				// 主键返回 user_id
				userdao.insertUser(user);
				// 插入id,oauth_id,oauth_type到oauth表
				logger.info("user_id:{}, oauth_id:{}, oauth_type:{}", user.getUserId(), oauthId, oauthType);
				oauth.setUserId(user.getUserId());
				oauth.setOauthId(oauthId);
				oauth.setOauthType(oauthType);
				// logger.info("user_id:{}, oauth_id:{}, oauth_type:{}",
				// user.getUserId(), oauth_id, oauth_type);
				oauthDao.insertOauth(oauth);
				onlineMap.put(user.getUserId(), (int) (System.currentTimeMillis() / 1000));
				ssoMap.put(user.getUserId(), deviceId);
				// 返回用户 信息
				LoginInfo login = new LoginInfo();
				// 生成一个token
				String tmpStr = oauthId + "," + System.currentTimeMillis();
				String token = UtilsDto.crypt(tmpStr);
				// 把token存入login_info
				login.setToken(token);
				login.setUserId(user.getUserId());
				login.setLoginTime(System.currentTimeMillis() / 1000);
				login.setHostAddr(hostAddr);
				login.setExpire(0);
				login.setLoginTime(2);
				logindao.insertloginfo(login);

				Account account = new Account();
				account.setUserId(user.getUserId());
				accountDao.insertAccount(account);

				// 把token存入jedisClient,以 字符串 的形式
				jedisClient.set(String.valueOf(TOKEN1 + oauth.getUserId()), token);
				jObject.put("result", "0");
				jObject.put("userId", oauth.getUserId());
				jObject.put("nickName", nickName);
				jObject.put("headPic", headPic);
				jObject.put("phoneNum", user.getPhoneNum());
				jObject.put("realName", user.getRealName());
				jObject.put("myRecommendCode", user.getMyRecommendCode());
				jObject.put("identityCard", user.getIdentityCard());
				jObject.put("token", token);
			}
		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "6");
			jObject.put("msg", "登陆失败");
		}
		return jObject.toJSONString();
	}

	// // 随机生成6位数字 的验证码
	// public static int getRandNum(int min, int max) {
	// int randNum = min + (int) (Math.random() * ((max - min) + 1));
	// return randNum;
	// // return String.valueOf(randNum);
	// }
	//
	// public static String rand5Code() {
	//
	// String zimu =
	// "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	// int index;
	// String ret = "";
	// for (int i = 0; i < 5; i++) {
	// index = getRandNum(0, 10000) % 62;
	// ret = ret + zimu.charAt(index);
	// }
	// return ret;
	// }

	// 验证码接口
	@Override
	public void cationcode(String deviceId, String vercode) {

		// 生成数子验证码
		// String vercode = getRandNum(1, 999999);

		// 生成的验证码以key（deviceId）存储进 jedis
		jedisClient.set(LOGINSYSTEM + deviceId, vercode);
		// 生成的时效性
		jedisClient.expire((LOGINSYSTEM + deviceId), 60 * 5);
		logger.info("SetdeviceId={}, vercode={}", deviceId, vercode);
		// 存放发到jedis中
		// return jObject.toJSONString();

	}

	// 短信验证码的接口
	@Override
	public String Sms(String deviceId, String phoneNum, String vercode, int smsFlag) {

		JSONObject jObject = new JSONObject();
		if (null == deviceId || null == phoneNum || null == vercode) {
			jObject.put("result", "1");
			jObject.put("msg", "参数不对");
			return jObject.toJSONString();
		}
		try {
			// 服务端自动生成的验证码存储在jedis中的取出来
			String vercode1 = jedisClient.get(LOGINSYSTEM + deviceId);

			logger.info("getdeviceId={}, vercode1={}", deviceId, vercode1);
			jedisClient.del(LOGINSYSTEM + deviceId);

			// 用取出的验证码和用户 输入 的验证码 进去 对比
			if ("".equals(vercode.trim()) || !vercode.equalsIgnoreCase(vercode1)) {
				jObject.put("result", "2");
				jObject.put("msg", "验证码不正确！");
				return jObject.toJSONString();
			}

			if (phoneNum.startsWith("1") && phoneNum.length() == 11) {
				try {
					Long i = Long.parseLong(phoneNum);
					logger.info("phoneNum:{}", i);
				} catch (Exception e) {
					e.printStackTrace();
					jObject.put("result", "2");
					jObject.put("msg", "手机号不正确");
					return jObject.toJSONString();
				}
			} else {
				jObject.put("result", "2");
				jObject.put("msg", "手机号不正确");
				return jObject.toJSONString();
			}

			User one = userdao.findUserByUserName(phoneNum);

			if (smsFlag == 1) {
				// 检验用户 是否 存在
				if (one != null) {
					jObject.put("result", "3");
					jObject.put("msg", "手机号已注册");
					return jObject.toJSONString();
				}
			} else {
				if (one == null) {
					jObject.put("result", "4");
					jObject.put("msg", "手机号未注册");
					return jObject.toJSONString();
				}
			}

			// 随机生成验证码
			String code = String.format("%06d", RandCodeUtil.getRandNum(1, 999999));
			// 保存到jedis
			logger.info("smscode: {}", code);
			jedisClient.set(LOGINSYSTEM1 + phoneNum, code);
			jedisClient.expire(LOGINSYSTEM1 + phoneNum, 600);

			// 调用短信接口
			JavaSmsApi smsapi = new JavaSmsApi();

			String ret = smsapi.sendSms(phoneNum, code, SMSKEY, SMSSMARK);
			// 解析结果
			// 反序列化
			logger.debug("sms ret: {}", ret);
			JSONObject obj = JSON.parseObject(ret);

			if (obj.getInteger("code") == 0) {
				jObject.put("result", "0");
				jObject.put("msg", "ok");
				// jObject.put("smscode", code);
			} else {
				jObject.put("result", "5");
				jObject.put("msg", "短信验证码发送失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "6");
			jObject.put("msg", "短信验证码发送失败");
		}
		return jObject.toJSONString();

	}

	// 生成 一个不重复的deviceId
	@Override
	public String device() {
		// 生成 一个不重复 的deviceId
		String deviceId = UUID.randomUUID().toString();
		return deviceId;
	}

	// @Override
	// public String error() {
	// JSONObject jObject = new JSONObject();
	// jObject.put("result", "1");
	// jObject.put("msg", "验证码为不正确 ");
	// return jObject.toString();
	// }

	// 统计在线人数
	/*
	 * @Override public String sonlinenum(int userId, int pageNum, int pageSize) {
	 * // 判断pageNum=0时 ArrayList<Integer> ids = new ArrayList<>(); int skip =
	 * (pageNum - 1) * pageSize; Map<String, Object> maxmap = new HashMap<String,
	 * Object>(); List<Map<String, Object>> list = new ArrayList<Map<String,
	 * Object>>(); // 返回的信息 try { maxmap.put("result", "0");
	 * maxmap.put("onlineCount", onlineMap.size()); maxmap.put("array", list); if
	 * (onlineMap.size() <= skip || userId == 0) { // userid为0说明是游客，只返回在线人数 String
	 * json = JSON.toJSONString(maxmap, true); return json; }
	 *
	 * Set<Integer> set = onlineMap.keySet(); int index = 0; for (int id : set) {
	 * index++; if (index > skip) { ids.add(id); } if (index - skip >= pageSize) {
	 * break; } } List<User> userArray = userdao.selectByUserId(ids); for (User one
	 * : userArray) { Map<String, Object> map = new HashMap<String, Object>();
	 * map.put("userId", one.getUserId()); map.put("userName", one.getUserName());
	 * map.put("headPic", one.getHeadPic()); map.put("city", one.getCity());
	 * list.add(map); } maxmap.put("array", list); // Array数组中的 } catch (Exception
	 * e) { e.printStackTrace(); maxmap.put("result", "1"); maxmap.put("msg",
	 * "系统异常"); } String json = JSON.toJSONString(maxmap, true); return json; }
	 */

	@Override
	public String sonlinenum(int userId, int pageNum, int pageSize) {
		// 判断pageNum=0时
		ArrayList<Integer> ids = new ArrayList<>();
		int skip = (pageNum - 1) * pageSize;
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 返回的信息
		try {
			// s int onlineSize = onlineMap.size();
			logger.debug("sonlinenum skip:{}", skip);
			maxmap.put("result", "0");
			maxmap.put("onlineCount", onlineMap.size() + RobotUserService.arrayRobotOnline.size());
			if (onlineMap.size() + RobotUserService.arrayRobotOnline.size() <= skip || userId == 0) { // userid为0说明是游客，只返回在线人数
				maxmap.put("array", list);
				String json = JSON.toJSONString(maxmap, true);
				return json;
			}

			if (skip <= onlineMap.size()) {
				logger.debug("sonlinenum onlineMap.size:{}", onlineMap.size());
				Set<Integer> set = onlineMap.keySet();
				int index = 0;
				// set, 在线人数的用户id
				int num = 0;
				for (int id : set) {
					index++;
					num++;
					if (index > skip) {
						ids.add(id);
					}
					if (index - skip >= pageSize) {
						break;
					}
				}
				List<User> userArray = null;
				if (ids.size() != 0) {
					userArray = userdao.selectByUserId(ids);
					for (User one : userArray) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("userId", one.getUserId());
						map.put("userName", one.getUserName());
						map.put("headPic", one.getHeadPic());
						map.put("city", one.getCity());
						list.add(map);
					}
				}

				if (num < pageSize) {
					logger.debug("sonlinenum need:{}", pageSize - num);
					for (int i = 0; i < pageSize - num; i++) {
						if (RobotUserService.arrayRobotOnline.size() > i) {
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("userId", RobotUserService.arrayRobotOnline.get(i).getRobotId());
							map.put("userName", RobotUserService.arrayRobotOnline.get(i).getRobotName());
							map.put("headPic", RobotUserService.arrayRobotOnline.get(i).getRobotPic());
							list.add(map);
						}
					}
				}
			} else {
				int index = skip - onlineMap.size();
				logger.debug("sonlinenum arrayRobotOnline.size:{} -- {}", RobotUserService.arrayRobotOnline.size(),
						index);
				for (int i = 0; i < pageSize; i++) {
					Map<String, Object> map = new HashMap<String, Object>();
					if (RobotUserService.arrayRobotOnline.size() > index + i) {
						map.put("userId", RobotUserService.arrayRobotOnline.get(index + i).getRobotId());
						map.put("userName", RobotUserService.arrayRobotOnline.get(index + i).getRobotName());
						map.put("headPic", RobotUserService.arrayRobotOnline.get(index + i).getRobotPic());
						logger.debug("sonlinenum userId:{}", userId);
						list.add(map);
					}
				}
			}
			maxmap.put("array", list);
			// Array数组中的
		} catch (Exception e) {
			e.printStackTrace();
			maxmap.put("result", "1");
			maxmap.put("msg", "系统异常");
		}
		String json = JSON.toJSONString(maxmap, true);
		return json;
	}

	// 退出
	@Override
	public void Logout(int userId, int loginType) {
		// 先客户自主选择退出，需要清空用户自身id,并删除自身token
		if (loginType == 0) {
			onlineMap.remove(userId);
			ssoMap.remove(userId);
			jedisClient.del(TOKEN + userId);
			CustomerContext customerContext = CustomerContext.getInstance();
			customerContext.userFinishServer(userId);
		} else {
			TouristData.touristInfo.remove(userId);
			TouristData.touristBetting.remove(userId);
			TouristData.touristWin.remove(userId);
			TouristData.touristPc28Betting.remove(userId);
			TouristData.touristPc28Win.remove(userId);
			jedisClient.del(TOKEN + userId);
		}
	}

	// 心跳包
	@Override
	public String heartbeat(int userId, String deviceId) {
		JSONObject jObject = new JSONObject();
		// 覆盖用户的时间戳
		User user = userdao.selectId(userId);
		if (user.getState().equals("0")) {
			jObject.put("result", "2");
			jObject.put("msg", "用户被冻结，请联系客服");
			return jObject.toString();
		}

		onlineMap.put(userId, (int) (System.currentTimeMillis() / 1000));
		String did = ssoMap.get(userId);
		if (did != null && !deviceId.equals(did)) {
			logger.info("{}--{}", deviceId, did);
			jObject.put("result", "1");
			jObject.put("msg", "用户在其他地方登录，强行退出登录");
		} else {
			jObject.put("result", "0");
			jObject.put("msg", "成功");
		}

		return jObject.toString();
	}

}
